package lumis.service.wiki;

import javax.persistence.Query;

import lumis.doui.processaction.IProcessActionHandler;
import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.manager.ManagerFactory;

/**
 * Verifies if the title is in use by another article.
 * 
 * @version $Revision: 10825 $ $Date: 2009-08-04 12:36:40 -0300 (Tue, 04 Aug 2009) $
 * @since 5.0.0
 */
public class ValidateArticleTitleProcessActionHandler extends ProcessActionHandler<Source<?>> implements IProcessActionHandler
{
	/**
	 * If the title is in use by other version, throws an exception.
	 * @since 5.0.0
	 */
	public void processAction() throws PortalException
	{
		String contentTitle = getParameter("title", String.class);
		String itemId = getParameter("id", String.class);
		String serviceInstance = douiContext.getRequest().getServiceInstanceConfig().getId();

		if (isTitleInUse(contentTitle, serviceInstance, itemId)) 
			throw new PortalException(localize("STR_ARTICLE_TITLE_IN_USE"));
	}

	/**
	 * Indicates if a title is in use by another article.
	 * @param contentTitle the title of the article.
	 * @param serviceInstanceId the article's service instance identifier.
	 * @param itemId the article's identifier if it is being edited, or null if it is being added.
	 * @return true if it is in use, false otherwise. 
	 * @since 5.0.0
	 */
	private boolean isTitleInUse(String contentTitle, String serviceInstanceId, String itemId) throws PortalException
	{
		Query content = ManagerFactory.getEntityManager().createQuery(
				"select count(*) from Content content inner join " +
				"content.contentLocales locale inner join " +
				"locale.activeVersion actVersion " +
				"where actVersion.primaryName = :contentTitle and " +
				"content.serviceInstanceId = :serviceInstance " +
				(itemId != null ? " and locale <> " +
						"(select v.contentLocale from ContentVersion v where v.itemId = :itemId)" : ""));
		
		if (itemId != null)
			content.setParameter("itemId", itemId);
		content.setParameter("serviceInstance", serviceInstanceId);
		content.setParameter("contentTitle", contentTitle);

		int versionCount = ((Number)content.getSingleResult()).intValue();
		return versionCount > 0;
	}
}